package com.coder520.login.controller;

import com.coder520.user.entity.User;
import com.coder520.user.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

@Controller
@RequestMapping("login")
public class LoginController {

    @Autowired
    private UserService userService;

    /**
     * @Author: Lin
     * @Param:  * @param
     * @Description: 登录界面
     * @Date: 18:01 2017/9/12
     */
    @RequestMapping
    public String login(){

        return "login";
    }

    /**
     * @Author: Lin
     * @Param:  * @param request
     * @Description: 校验登录
     * @Date: 16:49 2017/9/12
     */
    @RequestMapping("/check")
    @ResponseBody
    public String checkLogin(HttpServletRequest request) throws UnsupportedEncodingException, NoSuchAlgorithmException {

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
//        token.setRememberMe(true);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            SecurityUtils.getSubject().getSession().setTimeout(1800000);
        } catch (Exception e) {
            return "login_fail";
        }
        return "login_succ";

        ////查询数据库，调用MD5进行校验
        //User user = userService.findUserByUsername(username);
        //
        //if(user!=null){
        //    if(MD5Utils.checkPassword(password,user.getPassword())){
        //        //校验成功
        //
        //        //用户信息存储session中
        //        request.getSession().setAttribute("user",user);
        //
        //        return "login_succ";
        //    }else {
        //        //密码校验失败
        //        return "login_fail";
        //    }
        //}else {
        //    //用户不存在，校验失败
        //    return "login_fail";
        //}

    }

    @RequestMapping("/register")
    @ResponseBody
    public String registerUser(@RequestBody User user) throws UnsupportedEncodingException, NoSuchAlgorithmException {

        userService.createUser(user);

        return "succ";
    }
}
